#include <QDebug>
#include <QCompleter>
#include <QDir>
#include <QStringListModel>
#include <QStringBuilder>
#include "SelectFileName.h"

SelectFileName::SelectFileName(QWidget *parent) :
    QLineEdit(parent)
{
    connect(this, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
    connect(this, SIGNAL(editingFinished()), SLOT(onEditingFinished()));
    _normal = palette();
    _checkExisting = true;
    _isDir = false;
}

void SelectFileName::setBasePath(const QString & path)
{
    _path = path;
    QDir dir(path);
    QStringListModel *model = new QStringListModel(dir.entryList(), this);
    QCompleter *comp = new QCompleter(this);
    comp->setCaseSensitivity(Qt::CaseInsensitive);
    comp->setModel(model);
    setCompleter(comp);
}

void SelectFileName::setCheckExisting(bool existing)
{
    _checkExisting = existing;
}

void SelectFileName::onTextChanged(const QString & /*text*/)
{
    if (exists() && _checkExisting){
        QPalette pal = palette();
        pal.setColor(QPalette::Text, Qt::red);
        setPalette(pal);
    } else {
        setPalette(_normal);
    }
}

bool SelectFileName::exists()
{
    return QFile::exists(fullFileName());
}

void SelectFileName::setExtension(const QString & ext)
{
    _extension = ext;
}

QString SelectFileName::fullFileName()
{
    QString path = _path % QDir::separator() % text().trimmed();
    if (!_isDir) {
        QFileInfo info(path);
        if (info.suffix() == "" && !_extension.isEmpty()){
            path += info.fileName().right(1) == "." ? _extension : "." % _extension;
        }
    }
    return path;
}

void SelectFileName::onEditingFinished()
{
    normFileName();
}

void SelectFileName::normFileName()
{
    QFileInfo info(fullFileName());
    if (text() != info.fileName()){
        setText(info.fileName());
    }
}

void SelectFileName::setDirRequest(bool isdir)
{
    _isDir = isdir;
}

void SelectFileName::setBaseName(const QString& name)
{
    QString path = _path % QDir::separator() % name.trimmed();
    if (!_isDir) {
        QFileInfo info(path);
        if (info.suffix() == "" && !_extension.isEmpty()){
            path += info.fileName().right(1) == "." ? _extension : "." % _extension;
        }
    }
    setText(QFileInfo(path).fileName());
}
